<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><router-link to="/customer/customerNews">客户管理</router-link></el-breadcrumb-item>
        <el-breadcrumb-item>编辑客户</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <basic-container>
      <el-form :model="categoryForm" label-width="120px" label-position="right">
        <el-row class="m-b-hg">
          <h2>基础资料</h2>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input v-model="categoryForm.customerName" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户类型" required>
              <el-select class="fill-width" v-model="categoryForm.customerType" style="float: left" placeholder="请选择">
                <el-option
                  v-for="item in ctype"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户联系人">
              <el-input v-model="categoryForm.contact" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="客户经理">
              <el-select 
                filterable
                class="fill-width" 
                remote 
                :remote-method="remoteStaffList"
                v-model="categoryForm.directorId" 
                placeholder="请选择">
                <el-option
                  v-for="item in staffList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户标签">
              <el-select 
                class="fill-width"
                v-model="categoryForm.tags"
                multiple
                allow-create
                filterable 
                placeholder="请填写标签"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人手机" required>
              <el-input type="number" v-model="categoryForm.telephone" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="客户级别">
              <el-rate style="text-align: left;margin-top: 8px;" v-model="categoryForm.customerLevel"></el-rate>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售区域" required>
              <el-cascader 
                filterable
                class="fill-width"
                clearable
                v-model="categoryForm.areaSn" 
                :options="areaList"
                :change-on-select="true"
                @change="handleChangeArea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市场">
              <el-select 
                clearable
                filterable 
                remote
                :remote-method="remoteMarket" 
                class="fill-width" 
                v-model="categoryForm.marketSn" 
                placeholder="请选择">
                <el-option
                  v-for="item in marketList"
                  :key="item.marketSn"
                  :label="item.marketName"
                  :value="item.marketSn"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="客户状态">
              <el-select class="fill-width" v-model="categoryForm.status" style="width: 100%;float: left" placeholder="请选择">
                <el-option key="0" label="未启用" value="0"></el-option>
                <el-option key="1" label="启用" value="1"></el-option>
                <el-option key="2" label="待审核" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司性质">
              <el-select v-model="categoryForm.companyNature" style="width: 100%;float: left" placeholder="请选择">
                <el-option key="1" label="个体" value="1"></el-option>
                <el-option key="2" label="民营" value="2"></el-option>
                <el-option key="3" label="国有" value="3"></el-option>
                <el-option key="4" label="其他" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="座机电话">
              <el-input v-model="categoryForm.phoneNumber" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="标注位置" required>
              <p style="text-align: left">{{position.formattedAddress}}</p>
              <avue-map @input="changePosition" v-model="position" style="width:200px" :lnglat="lnglat"></avue-map>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="详细地址">
              <el-input v-model="categoryForm.address" type="textarea" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="门头照" required>
              <div v-if="categoryForm.photoList" class="thumbUrl" v-for="(item,index) in categoryForm.photoList">
                <img :src="item.picUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img(0)" style="float: left;"><i class="el-icon-plus"></i></div>
              <div v-if="sleImg">
                <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
                  <sel-img-photogallery ref="selImg" :type="selImgType" @select="onSelectImgs"></sel-img-photogallery>
                </el-dialog>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="m-b-hg">
          <h2>扩展资料</h2>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="营业时间描述">
              <el-input v-model="categoryForm.serviceTime" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年经营流水">
              <el-input v-model="categoryForm.shopSale" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经营面积">
              <el-input v-model="categoryForm.operateArea" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="经营法人名称">
              <el-input v-model="categoryForm.legalName" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照编码">
              <el-input v-model="categoryForm.bizLicense" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照名称">
              <el-input v-model="categoryForm.licenseName" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="经营地址">
              <el-input v-model="categoryForm.regAddress" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工商注册号">
              <el-input v-model="categoryForm.registrationNum" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户注册全称">
              <el-input v-model="categoryForm.regName" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="注册时间">
              <el-date-picker
                class="fill-width"
                v-model="categoryForm.registrationDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="传真">
              <el-input v-model="categoryForm.fax" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网址">
              <el-input v-model="categoryForm.website" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="邮编">
              <el-input v-model="categoryForm.postcode" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务介绍">
              <el-input type="textarea" v-model="categoryForm.bizDesc" class="form-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input v-model="categoryForm.remarks" type="textarea" class="form-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="营业执照">
              <div v-if="categoryForm.licensePhotoList" class="thumbUrl" v-for="(item,index) in categoryForm.licensePhotoList">
                <img :src="item.picUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img(1)" style="float: left;"><i class="el-icon-plus"></i></div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <div>
            <el-button type="primary" size="medium" @click="save">保存</el-button>
            <el-button type="default" size="medium" @click="close">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </basic-container>

  </div>
</template>

<script>
  import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery';
  import { areaTree } from '@/api/crm/area';
  import { addCustomer } from '@/api/crm/customer';
  import { getDetail }from '@/api/crm/customerList';
  import { formatCascader } from '@/const/common/tool';
  import { mapGetters } from 'vuex';
  import { fetchList as staffListApi } from '@/api/crm/marketemployee';
  import { fetchList as marketListApi } from '@/api/crm/marketmanage';
  export default {
    data() {
      return {
        categoryForm:{
          photoList:[],
          bizLicense:'',
          customerLevel:0,
          position:''
        },
        position:{
          formattedAddress:'',
          addressComponent:{
            city:'',
            district:'',
            province:'',
            township:''
          },
          longitude:'',
          latitude:''
        },
        sleImg:false,
        ctype:[{
          value:'1',
          name:'经销商'
        },{
          value:'2',
          name:'门店'
        }],
        //初始化坐标
        lnglat: {
          P: 29.563761,
          R: 106.55046400000003,
        },
        areaList:[],
        selImgType: '00',
        imgType:0,
        staffList: [],
        marketList: [],
      }
    },
    components: {  selImgPhotogallery },
    computed: {
      ...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
      tagLen() {
        return this.tagList.length || 0
      }
    },
    mounted() {

    },
    created(){
      this.getList();
      this.init();
      this.getStaffList();
      // this.getMarketList({current: 1, size: 100});
    },
    methods: {
      init(){
        let params ={};
        params.customerSn = JSON.parse(this.$route.query.res).customerSn;
        getDetail(params).then(response => {
          this.categoryForm = response.data.data;
          this.getMarketList({areaSn: this.categoryForm.areaSn});
          this.categoryForm.tags = this.categoryForm.tags ? this.categoryForm.tags.split(','):[];
          this.categoryForm.customerLevel = parseInt(response.data.data.customerLevel);
          this.position.formattedAddress = response.data.data.province + response.data.data.city+response.data.data.district+response.data.data.street
          this.position.addressComponent.province = response.data.data.province
          this.position.addressComponent.city = response.data.data.city
          this.position.addressComponent.district = response.data.data.district
          this.position.addressComponent.township = response.data.data.street
          let tmp =  response.data.data.position.split(',');
          this.lnglat = {P: Number(tmp[1]),R:Number(tmp[0])}
          this.position.latitude = Number(tmp[1]);
          this.position.longitude = Number(tmp[0]);
        })
      },
      //获取销售区域
      getList(page, params) {
        this.tableLoading = true
        areaTree({current: 1, size: 1000}).then(response => {
          this.areaList = formatCascader(response.data.data, 'areaName', 'areaSn');
        })
      },
      async remoteStaffList(name) {
        let query = {};
        if(name) query.name = name;
        let res = await staffListApi(Object.assign(query, {current: 1, size: 50}));
        this.staffList = res.data.data.records;
      },
      async getStaffList() {
        let res = await staffListApi({current: 1, size: 100});
        this.staffList = res.data.data.records;
      },
      async remoteMarket(marketName) {
          let areaSn = '';
          let value = this.categoryForm.areaSn;
          if(typeof this.categoryForm.areaSn === 'string') areaSn = this.categoryForm.areaSn;
          if(Array.isArray(value) && value.length > 0) areaSn = value[value.length -1];
          let res = await marketListApi({areaSn, marketName, current: 1, size: -1});
          this.marketList = res.data.data.records;
      },
      changePosition(data) {
        this.categoryForm.address = data.formattedAddress;
      },
      handleChangeArea(value) {
          this.categoryForm.marketSn = '';
          let areaSn = '';
          if(Array.isArray(value) && value.length > 0) areaSn = value[value.length -1];
          this.getMarketList({areaSn});
      },
      async getMarketList(params) {
        let res = await marketListApi(Object.assign({size:-1},params));
        this.marketList = res.data.data.records;
      },
      sel_img(t){
        this.imgType = t;
        if(this.imgType === 1) {
          this.selImgType = '05';
          if(this.categoryForm.licensePhotoList.length > 4) return this.$message.warning('最多上传5张营业执照');
        }else {
          this.selImgType = '00';
          if(this.categoryForm.photoList.length > 4) return this.$message.warning('最多上传5张门头照');
        }
        this.sleImg = true;
      },
      onSelectImgs(imgs){
        imgs.forEach((item)=>{
          if(this.imgType === 1 ){
            this.categoryForm.licensePhotoList.push({id:item.id,picUrl:item.picUrl})
          } else {
            this.categoryForm.photoList.push({id:item.id,picUrl:item.picUrl})
          } 
          
        })
        this.sleImg = false;
      },
      // 删除el-upload的图片
      handlePictureRemove(type,index) {
        if(type == 1){
          this.categoryForm.bizLicense = '';
        }else{
          this.categoryForm.photoList.splice(index,1)
        }
      },
      //确定
      save(){
        let tmp = []
        this.categoryForm.photoList.forEach((item)=>{
          tmp.push(item.id);
        })
        let params = JSON.parse(JSON.stringify(this.categoryForm));
        params.photoList = tmp;
        params.licensePhotoList = params.licensePhotoList.map((item)=>{
          return item.id;
        })
        if(Array.isArray(params.areaSn)) {
          if(params.areaSn.length > 0) {
            params.areaSn = params.areaSn[params.areaSn.length -1];
          }else {
            params.areaSn = '';
          }
        }
        if(Array.isArray(params.areaSn) && params.areaSn.length > 0) params.areaSn = params.areaSn[params.areaSn.length -1];
          params.tags = (Array.isArray(params.tags) && params.tags.length > 0) ?params.tags.join(','):'';
          if(this.position.longitude && this.position.latitude){
              params.position = this.position.longitude + ',' + this.position.latitude
          }
        params.province = this.position.addressComponent.province;
        params.city = this.position.addressComponent.city;
          if(params.province === '重庆市' || params.province === '北京市' || params.province === '上海市' || params.province === '天津市' || params.province === '香港特别行政区' || params.province === '澳门特别行政区'){
          params.city = params.province;
        }
        params.district = this.position.addressComponent.district;
        params.street = this.position.addressComponent.township;
        addCustomer(params).then(response => {
          if(response.data.code == 0){
            this.$message.success('编辑成功')
            let _this = this;
            setTimeout(function () {
              _this.close();
            },2000)
          }else{
            this.$message.success(response.data.msg)
          }
        })
      },
      close(){
        var str_before = location.href.split('#')[1];
        let { tag, key } = this.findTag(str_before);
        this.$store.commit('DEL_TAG', tag);
        this.$router.push({path: '/customer/customerNews'});
      },
      findTag(value) {
        let tag, key
        this.tagList.map((item, index) => {
          if (item.value === value) {
            tag = item
            key = index
          }
        })
        return { tag: tag, key: key }
      }
    }
  }
</script>

<style scoped lang="scss">
  .crumbs{
    margin: 20px 10px;
  }
  .thumbUrl{
    width: 150px;
    height: 150px;
    position: relative;
    line-height: 146px;
    float: left;
    margin-right: 15px;
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid #c0ccda;
  }
  .thumbUrl img{
    width: 100%;
    height: 100%;
  }
  .thumbUrl .hover_show{
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    display: none;
    text-align: center;
  }
  .thumbUrl:hover .hover_show{
    display: block;
  }
  .thumbUrl .hover_show i{
    color: #fff;
    margin: 0 10px;
    cursor: pointer;
  }
  .select_img{
    width: 148px;
    height: 148px;
    line-height: 146px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 28px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
    text-align: center;
  }
</style>


